﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Text;
using System.Configuration;
using RMS.DB;
using System.Management;

namespace RMS.Common
{
    internal class Utilities
    {

        public static string ProcessorID()
        {
            ManagementObjectCollection mbsList = null;
            ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_processor");
            mbsList = mbs.Get();
            string id = "";
            foreach (ManagementObject mo in mbsList)
            {
                id = mo["ProcessorID"].ToString();
            }

            return id;
        }

        #region common
        public static int PrecisionFormat = DecimalPlaces();
        public static int DecimalPlaces()
        {            
            ShopInfoManager mng = new ShopInfoManager();
            var info = mng.GetOne();
            if ( info == null) return 0;
            return info.DecimalPlaces;
            
        }
        private static readonly string ConStr = "Data source=" + Path.GetFullPath(Constants.DataPath);
        private static SQLiteConnection sql_con;
        private static SQLiteCommand sql_cmd;

        private static void SetConnection()
        {
            sql_con = new SQLiteConnection(ConStr);
        }

        private static void ExecuteQuery(string txtQuery)
        {
            SetConnection();
            sql_con.Open();
            sql_cmd = sql_con.CreateCommand();
            sql_cmd.CommandText = txtQuery;
            sql_cmd.ExecuteNonQuery();
            sql_con.Close();
        }

        public static string Lisence(string input)
        {
            var temp = Encrypt(input);
            if (temp != string.Empty)
            {
                var count4 = 0;
                StringBuilder output = new StringBuilder();
                for (int i = 0; i < temp.Length; i++)
                {
                    output.Append(temp[i]);
                    count4 = count4 + 1;

                    if (count4 == 4 && i != (temp.Length - 1))
                    {
                        output.Append("-");
                        count4 = 0;
                    }
                }

                return output.ToString();
            }

            return "";
        }
        public static string Encrypt(string mess)
        {
            MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(mess);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString().ToUpper();
        }

        #endregion

        #region Connect Database

        public static DataTable GetDatatable(string tableName)
        {
            try
            {
                SQLiteDataAdapter DB;
                var DS = new DataSet();
                var DT = new DataTable();
                DateTime a = DateTime.Now;
                SetConnection();
                sql_con.Open();

                sql_cmd = sql_con.CreateCommand();
                string CommandText = "select * from " + tableName;
                DB = new SQLiteDataAdapter(CommandText, sql_con);
                DS.Reset();
                DB.Fill(DT);
                sql_con.Close();
                return DT;
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return null;
            }
        }

        #endregion

        #region Check valid login name

        public static string CheckLoginUser(string username, string pass)
        {
            string check = "0"; // false
            var secu = new DataTable();
            secu = GetDatatable(Constants.Login.Table_Name);
            foreach (DataRow row in secu.Rows)
            {
                if (Convert.ToString(row[Constants.Login.Column.User_Name]).Equals(username))
                {
                    if (Convert.ToString(row[Constants.Login.Column.Password]).Equals(pass))
                    {
                        if (Convert.ToString(row[Constants.Login.Column.IsAdmin]).Equals("True"))
                            check = "1#1"; // true , admin
                        else
                            check = "1#0"; // true, not admin
                    }
                }
            }
            return check;
        }

        #endregion

        #region Search

        public static DataTable SearchItem(string id, string tableName)
        {
            try
            {
                SQLiteDataAdapter DB;
                var DS = new DataSet();
                var DT = new DataTable();
                DateTime a = DateTime.Now;
                SetConnection();
                sql_con.Open();

                sql_cmd = sql_con.CreateCommand();
                string CommandText = "select * from " + tableName + "where ID = " + id;
                DB = new SQLiteDataAdapter(CommandText, sql_con);
                DS.Reset();
                DB.Fill(DT);
                sql_con.Close();
                return DT;
            }
            catch (Exception)
            {
                MessageBox.Show(Constants.Msg.ConnectError);
                return null;
            }
        }

        #endregion

        #region VerifyAdmin
        public static string Encode(string originalPassword)
        {
            //Declarations
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;

            //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);

            //Convert encoded bytes back to a 'readable' string
            return BitConverter.ToString(encodedBytes);
        }

        public static bool VerifyAdmin(string admCode)
        {
            string verifyCode = System.IO.File.ReadAllText(Constants.VerifyAdminPath);
            var arr = verifyCode.Split('#');
            string encoded = Encode(admCode);
            if (arr[0].Equals(encoded))
                return true;
            else
                return false;
        }
        public static decimal DiscountPercent()
        {
            string verifyCode = System.IO.File.ReadAllText(Constants.VerifyAdminPath);
            var arr = verifyCode.Split('#');
            return Convert.ToDecimal(arr[1]);
        }
        public static bool IsEnableSaleprice()
        {
            string verifyCode = System.IO.File.ReadAllText(Constants.VerifyAdminPath);
            var arr = verifyCode.Split('#');
            return arr[2] == "1";
        }
        public static bool IsSaleOff()
        {
            string verifyCode = System.IO.File.ReadAllText(Constants.VerifyAdminPath);
            var arr = verifyCode.Split('#');
            return arr[3] == "1";
        }
        #endregion

        public static string UniqueString() // dd-mo-yy-hh-mi-ss-tt format
        {
            string code = "";
            string yy = DateTime.Now.Year.ToString().Substring(2, 2);
            string mo = DateTime.Now.Month.ToString("00");
            string dd = DateTime.Now.Day.ToString("00");
            string hh = DateTime.Now.Hour.ToString("00");
            string mi = DateTime.Now.Minute.ToString("00");
            string ss = DateTime.Now.Second.ToString("00");
            string tt = DateTime.Now.Millisecond.ToString("00");
            code = String.Format("{0}{1}{2}{3}{4}{5}{6}", yy, mo, dd, hh, mi, ss, tt);
            return code;
        }

        //public static bool NewerDate(DateTime d1, DateTime d2)
        //{
        //    if (d1.Year < d2.Year)
        //        return false;
        //    else if (d1.Month < d2.Month)
        //        return false;
        //    else if (d1.Day < d2.Day)
        //        return false;
        //    else
        //        return true;

        //}
        //public static bool LaterDate(DateTime d1, DateTime d2)
        //{
        //    if (d1.Year > d2.Year)
        //        return false;
        //    else if (d1.Month > d2.Month)
        //        return false;
        //    else if (d1.Day > d2.Day)
        //        return false;
        //    else
        //        return true;

        //}

        #region Format number

        public static string FormatNumber(decimal decInput)
        {           

            string precision = "{0:#,##0.";
            for (int i = 0; i < Utilities.PrecisionFormat; i++)
            {
                precision += "0";
            }
            precision += "}";
            return string.Format(precision, decInput);
        }

        public static string FormatNumber(decimal decInput, int intPrecision)
        {

            string precision = "{0:#,##0.";
            for (int i = 0; i < intPrecision; i++)
            {
                precision += "0";
            }
            precision += "}";
            return string.Format(precision, decInput);
        }
        #endregion
    }
}
